package cn.edu.tju.scs.leave.filter;

import cn.edu.tju.scs.leave.entity.User;
import cn.edu.tju.scs.leave.exception.UserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


public class LoginInterceptor implements HandlerInterceptor {

	private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	private List<String> excludedUrls;

	public void setExcludedUrls(List<String> excludedUrls) {
		this.excludedUrls = excludedUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		// excluded URLs:
		String requestUri = request.getRequestURI();
		logger.info("请求的uri:" + requestUri);
		System.out.println("请求的uri:" + requestUri);
		for (String url : excludedUrls) {
			if (requestUri.endsWith(url)) {
				return true;
			}
		}

        logger.info("session id :" + request.getSession().getId());
        System.out.println("session id :" + request.getSession().getId());
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			throw new UserException(UserException.NOT_LOGIN_EXCEPTION);
//			return false;
		}
        return true;
	}

	@Override
	public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
			modelAndView)throws Exception {

		System.out.println("postHandle");

//		int len = 0;
//		//5.创建数据缓冲区
//		byte[] buffer = new byte[1024];
//		 //6.通过response对象获取OutputStream流
//		 OutputStream out = response.getOutputStream();
//		//7.将FileInputStream流写入到buffer缓冲区
//		while ((len = in.read(buffer)) > 0) {
//			//8.使用OutputStream将缓冲区的数据输出到客户端浏览器
//			out.write(buffer,0,len);
//		}
		System.out.println(request);
	}

	@Override
	public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
		System.out.println("afterCompletion");
	}
}
